import json
import re
import uuid

from rest_framework.pagination import PageNumberPagination
from rest_framework.viewsets import ModelViewSet
from rest_framework_jwt.utils import jwt_decode_handler
from django.contrib.auth.backends import ModelBackend
from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.generics import CreateAPIView
from rest_framework.permissions import IsAuthenticated, BasePermission
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_jwt.settings import api_settings

from store.models import StoreManagement, UserAndStore
from users import constants, serializers
from users.models import User, RegisterCode, RoleMenu, RolePermission, UserRole, Permission, Menu, Role
# from users.serializers import UserLoginSerializer
from users.serializers import ReturnStaffAndStoreSerializer, CreateRegisterCodeSerializer, \
    CreateRegisterCodeSerializer2, RoleMenuSerializer, RolePermissionListSerializer, RolePermissionSerializer, \
    UserRoleListSerializer, UserRoleSerializer, PermissionSerializer, MenuSerializer, UserSerializer, \
    UserListSerializer, AddUserSerializer, RoleSerializer, UserRolesListSerializer, UserRolesListSerializer2, \
    RolePermissionsListSerializer, RolePermissionsListSerializer2, RoleMenusListSerializer1, RoleMenusListSerializer2
from vne_erp.libs.captcha.captcha import captcha


class UserInfoView(APIView):

    # permission_classes = [IsAuthenticated]
    def get(self,request):
        test = request.META.get('HTTP_AUTHORIZATION')
        jwt_token = test.split(' ')[1]
        # print(jwt_decode_handler(jwt_token))
        user = request.user
        # print(user)
        try:
            user_store = StoreManagement.objects.filter(staff=user.id)
        except Exception as e:
            return Response({"error_msg":str(e)}, status=status.HTTP_404_NOT_FOUND)
        data = {
            "username": user.username,
            "email": user.email,
            "mobile": user.mobile,
            "is_superuser": user.is_superuser,
            "data_join": user.date_joined,
            "user_stores": [i.store for i in user_store]
        }
        return Response(data)


# class UserLoginView(APIView):
#     # serializer_class = serializers.UserLoginSerializer
#
#     def post(self, request):
#         serializer = UserLoginSerializer(data=request.data)
#         serializer.is_valid(raise_exception=True)
#         username = serializer.validated_data.get('username')
#         user_id = serializer.validated_data.get('user_id')
#         token = serializer.validated_data.get('token')
#
#         response_data = {
#             "username": username,
#             "user_id": user_id,
#             "token": token
#         }
#
#         return Response(response_data)


class UserRegisterView(CreateAPIView):
    """用户注册"""
    serializer_class = serializers.CreateUserSerializer


class UsernameExist(APIView):

    def get(self, request, username):
        """获取指定用户数量"""
        try:
            user_count = User.objects.filter(username=username).count()
        except Exception as e:
            return Response({"error_msg": str(e)})
        data = {
            "user_count": user_count,
            "username": username
        }

        return Response(data)


class ImageCodeView(APIView):

    def get(self, request, image_code_id):
        """返回图片验证码"""

        text, image = captcha.generate_captcha()
        # print(text)
        # print(image_code_id)

        redis_conn = get_redis_connection("image_codes")

        # redis_conn.set(image_code_id, text)

        redis_conn.setex("img_%s" % image_code_id, constants.IMAGE_CODE_REDIS_EXPIRES, text)

        return HttpResponse(image, content_type="image/jpg")


class GetUserList(APIView):
    def get(self, request):
        """返回员工列表"""

        users = User.objects.all()
        # print(users)
        username_list = list()
        for i in users:

            username_list.append(i.username)

        return Response({"success_msg": username_list})


class CreateRegisterCodeView(APIView):

    def get(self,request):
        """新增注册码"""
        number = request.query_params.get("number")
        for i in range(0, int(number)):
            register_code = {"register_code":str(uuid.uuid4())}
            serializer = CreateRegisterCodeSerializer(data=register_code)
            serializer.is_valid(raise_exception=True)
            serializer.save()

        return Response({"success_msg":f"新增{number}个注册码成功"}, status=status.HTTP_201_CREATED)

class ListRegisterCodeView(APIView):
    def get(self,request):
        register_codes = RegisterCode.objects.all()
        serializer = CreateRegisterCodeSerializer2(data=register_codes, many=True)
        serializer.is_valid()

        # data = {"status_true": [],'status_false':[]}
        # for i in serializer.data:
        #     if i.get("status"):
        #         data['status_true'].append(i.get("register_code"))
        #     else:
        #         data['status_false'].append(i.get("register_code"))
        return Response({"success_msg": serializer.data})


class ReturnStaffAndStoreView(APIView):
    def get(self, request):
        """查询所有员工已授权和可授权的所有店铺"""
        # users = User.objects.filter(staff_group=1)
        users = User.objects.all()
        user_store_list = list()
        for i in users:
            user_store_dict = dict()
            user_stores = UserAndStore.objects.filter(staff=i.id)
            user_stores_exclude = StoreManagement.objects.all()
            stores = [store.store for store in user_stores]
            stores_exclude = [store for store in user_stores_exclude]
            store_list = list()
            store_list_exclude = list()
            for j in stores:
                store_dict = dict()
                store_dict['id'] = j.id
                store_dict['store'] = j.store
                store_list.append(store_dict)
            for j in stores_exclude:
                if j in stores:
                    continue
                store_dict = dict()
                store_dict['id'] = j.id
                store_dict['store'] = j.store
                store_list_exclude.append(store_dict)

            user_store_dict['id'] = i.id
            user_store_dict['username'] = i.username
            user_store_dict['stores'] = store_list
            user_store_dict['stores_exclude'] = store_list_exclude
            user_store_list.append(user_store_dict)

        return Response({"success_msg": user_store_list}, status=status.HTTP_200_OK)





"""良宝views """
class UserPageNumberPagination(PageNumberPagination):
    page_size = 20  # 每页显示多少条
    page_size_query_param = 'size'  # URL中每页显示条数的参数
    page_query_param = 'page'  # URL中页码的参数
    max_page_size = None  # 最大页码数限制

class UserViewSet(ModelViewSet):
    # permission_classes = [IsAuthenticated]
    queryset = User.objects.all()
    serializer_class = UserSerializer
    pagination_class = UserPageNumberPagination
    def list(self, request, *args, **kwargs):
        queryset =self.queryset
        page_obj = UserPageNumberPagination()
        page_article = page_obj.paginate_queryset(queryset=queryset, request=request, view=self)
        serializer = UserListSerializer(page_article, many=True)
        print(serializer.data)
        data = []
        # for i in serializer.data:
        #     i["userrole_set"]["role"]= i["userrole_set"]["role"]["name"]
        #     data.append(i)
        # response = page_obj.get_paginated_response(data)
        response = page_obj.get_paginated_response(serializer.data)
        return response

    def create(self, request, *args, **kwargs):
        data=request.data.copy()
        username = data.get('username')
        if username:
            try:
                user = User.objects.filter(username=username)
                print(user)
            except Exception as e:
                return Response({"error_msg": str(e)})
        else:
            return Response({"error_msg": "用户名不能为空"})
        if user:
            return Response({"error_msg": "该用户已存在"})
        password = data.get('password')
        password2 = data.get('password2')
        print(password,password2)
        if password and password2:
            if password == password2:
                data.pop('password2')
                serializer = AddUserSerializer(data=data)
                print(serializer)
                serializer.is_valid(raise_exception=True)
                serializer.save()
            else:
                return Response({"error_msg": "两次输入的密码不一致"})

        else:
            return Response({"error_msg": "密码和确认密码不能为空"})
        return Response('ok')


class RolePageNumberPagination(PageNumberPagination):
    page_size = 20  # 每页显示多少条
    page_size_query_param = 'size'  # URL中每页显示条数的参数
    page_query_param = 'page'  # URL中页码的参数
    max_page_size = None  # 最大页码数限制


class RoleViewSet(ModelViewSet):
    # permission_classes = [IsAuthenticated]
    queryset = Role.objects.all()
    serializer_class = RoleSerializer
    pagination_class = RolePageNumberPagination


class MenuPageNumberPagination(PageNumberPagination):
    page_size = 40  # 每页显示多少条
    page_size_query_param = 'size'  # URL中每页显示条数的参数
    page_query_param = 'page'  # URL中页码的参数
    max_page_size = None  # 最大页码数限制


class MenuViewSet(ModelViewSet):
    # permission_classes = [IsAuthenticated]
    queryset = Menu.objects.all()
    serializer_class = MenuSerializer
    pagination_class = MenuPageNumberPagination
    def list(self, request, *args, **kwargs):
        # print(self.queryset)
        queryset = Menu.objects.all()
        serializer = MenuSerializer(queryset,many=True)
        print(serializer.data)
        # data = self.menu_list(serializer.data)
        # print(data)
        a = []
        for i in serializer.data:
            i['child']=[]
            # print(i)
            a.append(i)
        # print(a)
        a = json.dumps(a)
        data = self.menu_list(a)
        print(data)
        return Response(data)
    @staticmethod
    def menu_list(menu_list):
        menu_list = json.loads(menu_list)
        menu_list1 = []
        b = menu_list.copy()
        for i in menu_list:
            if i['parent'] == None:
                menu_list1.append(i)
                b.remove(i)
        menu_list2 = []
        menu_list3 = b.copy()
        for i in menu_list1:
            for j in b:

                if i['id'] == j['parent']:
                    menu_list2.append(j)
                    menu_list3.remove(j)
        for i in menu_list2:
            for j in menu_list3:
                if i['id'] == j['parent']:
                    i['child'].append(j)
        for i in menu_list1:
            for j in menu_list2:
                if i['id'] == j['parent']:
                    i['child'].append(j)
        return menu_list1


class PermissionPageNumberPagination(PageNumberPagination):
    page_size = 20  # 每页显示多少条
    page_size_query_param = 'size'  # URL中每页显示条数的参数
    page_query_param = 'page'  # URL中页码的参数
    max_page_size = None  # 最大页码数限制


class PermissionViewSet(ModelViewSet):
    # permission_classes = [IsAuthenticated]
    queryset = Permission.objects.all()
    serializer_class = PermissionSerializer
    pagination_class = PermissionPageNumberPagination

    def list(self, request, *args, **kwargs):
        queryset = Permission.objects.all()
        params = request.query_params
        type = params.get('type')
        if type:
            queryset = queryset.filter(type=type)
        page_obj = PermissionPageNumberPagination()
        page_article = page_obj.paginate_queryset(queryset=queryset, request=request, view=self)
        serializer = PermissionSerializer(page_article, many=True)
        response = page_obj.get_paginated_response(serializer.data)
        return response


class UserRolePageNumberPagination(PageNumberPagination):
    page_size = 20  # 每页显示多少条
    page_size_query_param = 'size'  # URL中每页显示条数的参数
    page_query_param = 'page'  # URL中页码的参数
    max_page_size = None  # 最大页码数限制


class UserRoleViewSet(ModelViewSet):
    # permission_classes = [IsAuthenticated]
    queryset = UserRole.objects.all()
    serializer_class = UserRoleSerializer
    pagination_class = UserRolePageNumberPagination
    def list(self, request, *args, **kwargs):
        queryset = self.queryset
        page_obj =UserRolePageNumberPagination()
        page_article = page_obj.paginate_queryset(queryset=queryset, request=request, view=self)
        serializer = UserRoleListSerializer(page_article, many=True)
        response = page_obj.get_paginated_response(serializer.data)
        return response





class RolePermissionPageNumberPagination(PageNumberPagination):
    page_size = 20  # 每页显示多少条
    page_size_query_param = 'size'  # URL中每页显示条数的参数
    page_query_param = 'page'  # URL中页码的参数
    max_page_size = None  # 最大页码数限制


class RolePermissionViewSet(ModelViewSet):
    # permission_classes = [IsAuthenticated]
    queryset = RolePermission.objects.all()
    serializer_class = RolePermissionSerializer
    pagination_class = RolePermissionPageNumberPagination

class RoleMenuPageNumberPagination(PageNumberPagination):
    page_size = 20  # 每页显示多少条
    page_size_query_param = 'size'  # URL中每页显示条数的参数
    page_query_param = 'page'  # URL中页码的参数
    max_page_size = None  # 最大页码数限制


class RoleMenuViewSet(ModelViewSet):
    # permission_classes = [IsAuthenticated]
    queryset = RoleMenu.objects.all()
    serializer_class = RoleMenuSerializer
    pagination_class = RoleMenuPageNumberPagination
    # def list(self, request, *args, **kwargs):
    #     queryset = self.queryset

    #     page_obj =RoleMenuPageNumberPagination()
    #     page_article = page_obj.paginate_queryset(queryset=queryset, request=request, view=self)
    #     serializer = RoleMenuListSerializer(page_article, many=True)
    #     response = page_obj.get_paginated_response(serializer.data)
    #     return response

class UserRolesList(APIView):
    def get(self,request):
        params = request.query_params
        user_id = params.get('user_id')

        queryset = Role.objects.all()

        data1 = UserRolesListSerializer(queryset,many=True).data

        queryset2 = UserRole.objects.filter(user_id=user_id)

        data2 = UserRolesListSerializer2(queryset2, many=True).data

        rolelist = []
        for i in data2:
            rolelist.append(i['role'])

        data = {}
        data['roles'] = data1
        data['isdistributionlist'] = rolelist

        return Response(data)



class CreateUserRoles(APIView):
    def post(self,request):
        user_id = request.data.get('user_id')
        # rolelist_json = request.data.get('rolelist')
        # rolelist = json.loads(rolelist_json)
        rolelist = request.data.get('rolelist')

        queryset2 = UserRole.objects.filter(user_id=user_id)

        data2 = UserRolesListSerializer2(queryset2, many=True).data

        rolelist2 = []
        for i in data2:
            rolelist2.append(i['role'])


        del_list = list(set(rolelist2).difference(set(rolelist)))

        create_list = list(set(rolelist).difference(set(rolelist2)))


        for role in del_list:
            UserRole.objects.filter(user=user_id,role=role).delete()
        for role in create_list:

            data = {}
            data['user']=int(user_id)
            data['role'] = int(role)
            serializer = UserRolesListSerializer2(data=data)
            serializer.is_valid(raise_exception=True)
            serializer.save()
        return Response({"success_msg": "ok"},status=status.HTTP_201_CREATED)



class RolePermissionsList(APIView):
    def get(self, request):
        params = request.query_params
        role_id = params.get('role_id')
        queryset = Permission.objects.all()
        data1 = RolePermissionsListSerializer(queryset, many=True).data
        respose_data = {}
        data = {}
        data['首页'] = []
        data['订单'] = []
        data['数据统计'] = []
        data['采购'] = []
        data['店铺'] = []
        data['授权'] = []
        data['员工'] = []
        data['侵权'] = []
        data['库存'] = []
        data['权限'] = []
        for i in data1:
            if i['type'] == '首页':
                data['首页'].append(i)
            elif i['type'] == '订单':
                data['订单'].append(i)
            elif i['type'] == '数据统计':
                data['数据统计'].append(i)
            elif i['type'] == '数据统计':
                data['采购'].append(i)
            elif i['type'] == '采购':
                data['订单'].append(i)
            elif i['type'] == '店铺':
                data['店铺'].append(i)
            elif i['type'] == '授权':
                data['授权'].append(i)
            elif i['type'] == '员工':
                data['员工'].append(i)
            elif i['type'] == '侵权':
                data['侵权'].append(i)
            elif i['type'] == '库存':
                data['库存'].append(i)
            elif i['type'] == '权限':
                data['权限'].append(i)

        respose_data['roles'] = data
        queryset2 = RolePermission.objects.filter(role_id=role_id)
        data2 = RolePermissionsListSerializer2(queryset2, many=True).data
        permissionlist = []
        for i in data2:
            permissionlist.append(i['permission'])
        respose_data['isdistributionlist'] = permissionlist
        return Response(respose_data)


class CreateRolePermissions(APIView):
    def post(self,request):
        role_id = request.data.get('role_id')
        # permissionlist_json = request.data.get('permissionlist')
        # permissionlist = json.loads(permissionlist_json)
        permissionlist = request.data.get('permissionlist')


        queryset2 = RolePermission.objects.filter(role_id=role_id)

        data2 = RolePermissionsListSerializer2(queryset2, many=True).data

        permissionlist2 = []
        for i in data2:
            permissionlist2.append(i['permission'])


        del_list = list(set(permissionlist2).difference(set(permissionlist)))
        create_list = list(set(permissionlist).difference(set(permissionlist2)))


        for permission in del_list:
            RolePermission.objects.filter(role=role_id,permission=permission).delete()
        for permission in create_list:

            data = {}
            data['role']=int(role_id)
            data['permission'] = int(permission)
            serializer = RolePermissionsListSerializer2(data=data)
            serializer.is_valid(raise_exception=True)
            serializer.save()
        return Response({"success_msg": "ok"},status=status.HTTP_201_CREATED)




class RoleMenusList(APIView):
    def get(self,request):
        params = request.query_params
        role_id = params.get('role_id')
        queryset1 = Menu.objects.all()

        data1 = RoleMenusListSerializer1(queryset1,many=True).data

        a = []
        for i in data1:
            i['child']=[]
            a.append(i)
        data1 = self.menu_list(a)



        queryset2 = RoleMenu.objects.filter(role_id=role_id)

        data2 = RoleMenusListSerializer2(queryset2, many=True).data

        # return Response('ok')
        menulist = []
        for i in data2:
            menulist.append(i['menu'])

        data = {}
        data['roles'] = data1
        data['isdistributionlist'] = menulist

        return Response(data)


    @staticmethod
    def menu_list(menu_list):
        # menu_list = json.loads(menu_list)
        menu_list1 = []
        b = menu_list.copy()
        for i in menu_list:
            if i['parent'] == None:
                menu_list1.append(i)
                b.remove(i)
        menu_list2 = []
        menu_list3 = b.copy()
        for i in menu_list1:
            for j in b:

                if i['id'] == j['parent']:
                    menu_list2.append(j)
                    menu_list3.remove(j)
        for i in menu_list2:
            for j in menu_list3:
                if i['id'] == j['parent']:
                    i['child'].append(j)
        for i in menu_list1:
            for j in menu_list2:
                if i['id'] == j['parent']:
                    i['child'].append(j)
        return menu_list1





class CreateRoleMenus(APIView):
    def post(self,request):
        role_id = request.data.get('role_id')
        menulist_json = request.data.get('menulist')
        menulist = json.loads(menulist_json)
        # menulist = request.data.get('menulist')


        queryset2 = RoleMenu.objects.filter(role_id=role_id)

        data2 = RoleMenusListSerializer2(queryset2, many=True).data

        menulist2 = []
        for i in data2:
            menulist2.append(i['menu'])


        del_list = list(set(menulist2).difference(set(menulist)))
        create_list = list(set(menulist).difference(set(menulist2)))


        for menu in del_list:
            RoleMenu.objects.filter(role=role_id,menu=menu).delete()
        for menu in create_list:

            data = {}
            data['role']=int(role_id)
            data['menu'] = int(menu)
            serializer = RoleMenusListSerializer2(data=data)
            serializer.is_valid(raise_exception=True)
            serializer.save()
        return Response({"success_msg": "ok"},status=status.HTTP_201_CREATED)




class MyPermissionView(BasePermission):
    def has_permission(self, request, view):

        if request.user.is_staff:
            return True
        else:
            return False


class MyPermissionObj(BasePermission):
    def has_object_permission(self, request, view, obj):
        return False


class UserPermissionTest(APIView):

    permission_classes = [IsAuthenticated]

    # permission_classes = [AllowAny,MyPermissionView]
    # permission_classes = [AllowAny]

    def get(self, request):
        """返回员工列表"""
        # print("###:", request.user)
        # print("###:", dir(request.user))
        # print("###:",request.user.username)
        # print("###:",request.user.username)
        # id = request.query_params['id']
        # print("###:",id)
        # user = User.objects.get(id=id)
        # user.username = 'hertpp'
        # user.save()
        # print("###:",user,type(user))

        # user.user_permissions = []

        # print(user.get_all_permissions())
        # print(user.get_group_permissions())
        #
        # print(user.has_perm('orders.delete_paymentmethodddetails'))
        # print(user.has_perm('orders.change_productinfos'))

        # print(Permission.objects.get(pk=43))
        # user.user_permissions.add(Permission.objects.get(pk=43))
        #
        # qs = Group.objects.filter(user=user)
        # print(qs)

        # print(user.user_permissions.all())
        # group = Group.objects.get(id=3)
        # ret = group.delete()
        # print(ret)

        return Response({"success_msg": 'ok'})

# class CommissionRoleViewSet(ModelViewSet):
#     queryset = CommissionRole.objects.all()
#     print(queryset)
#     serializer_class = CommissionRoleSerializer
# class CommissionPermissionViewSet(ModelViewSet):
#     queryset = CommissionPermission.objects.all()
#     print(queryset)
#     serializer_class = CommissionPermissionSerializer
# class CommissionPermissionGroupViewSet(ModelViewSet):
#     queryset = CommissionPermissionGroup.objects.all()
#     print(queryset)
#     serializer_class = CommissionPermissionGroupSerializer




class Test(APIView):
    def get(self,request):
        import xmltodict
        from mws import mws

        access_key = 'AKIAITNXOMXBNOGOAHMQ'
        secret_key = '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'
        SellerId = "A1V087CKPQPJAJ"
        MWSToken = "amzn.mws.fab6a111-4a7b-3a35-7d14-9cbc6ac30a0a"

        # order_update_time = datetime.datetime(2019, 7, 1)
        #
        # CreatedAfter = isoformat(order_update_time)
        #
        x = mws.Reports(access_key=access_key, secret_key=secret_key, account_id=str(SellerId),
                        auth_token=str(MWSToken))
        try:
            # orders = x.list_orders(created_after=CreatedAfter, marketplaceids=marketplaceids)
            orders = x.get_report(report_id='16776752411018164')
        except Exception as e:
            print(str(e))

        response_data = orders.original
        datas = xmltodict.parse(response_data)
        return Response(datas)
